# -*-coding: Utf-8 -*-
# @File : User .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time：2023/10/11
from flask import Blueprint, request, render_template, session, redirect, jsonify

user_view = Blueprint('user', __name__, url_prefix='/user', template_folder='templates')


@user_view.route('/register', methods=['POST'])
def register():
    data = request.form
    username = data.get('username')
    password = data.get('password')
    if username and password:
        sql = f'select user_name from user where user_name = "{username}"'
        user_exists = request.mysql_handler.exec(sql)
        if user_exists:
            return jsonify({'code': 201, 'message': "用户已存在，不允许注册"})
        sql = f'insert into user(user_name,user_password) values ("{username}","{password}")'
        user_create = request.mysql_handler.exec(sql)
        if user_create:
            return jsonify({'code': 200, 'message': "注册成功"})
    return jsonify({'code': 201, 'message': "注册失败"})


@user_view.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        data = request.form
        username = data.get('username')
        password = data.get('password')
        sql = f'select user_name,user_password from user where user_name = "{username}" and user_password = "{password}"'
        user = request.mysql_handler.query(sql)
        session['username'] = user.get('user_name')
        if user:
            return jsonify({'code': 200, 'url': '/house/house_data'})
        else:
            return '用户名或密码错误'
    return render_template('login.html')


@user_view.route('/logout', methods=['GET'])
def logout():
    session.pop('username')
    return jsonify({'url': '/user/login'})
